/**
 * 拖拽排序Hook
 * Story 5: Task 6 - 拖拽排序功能
 */

import { useState, useCallback, useRef } from 'react'
import { useHapticFeedback } from './useHapticFeedback'
import { useGestureConflictHandler } from './useGestureConflictHandler'

interface DragReorderOptions<T> {
  items: T[]
  onReorder: (items: T[]) => void
  delay?: number // 延迟避免误触
  enabled?: boolean
}

interface DragState {
  isDragging: boolean
  dragIndex: number | null
  hoverIndex: number | null
}

/**
 * 拖拽排序Hook
 * 提供拖拽重排序功能，支持触觉反馈和误触防护
 */
export const useDragReorder = <T,>({
  items,
  onReorder,
  delay = 500,
  enabled = true,
}: DragReorderOptions<T>) => {
  const [dragState, setDragState] = useState<DragState>({
    isDragging: false,
    dragIndex: null,
    hoverIndex: null,
  })

  const dragTimerRef = useRef<NodeJS.Timeout>()
  const { trigger: triggerHaptic } = useHapticFeedback()
  const { startGesture, endGesture, canStartGesture } = useGestureConflictHandler()

  /**
   * 开始拖拽
   */
  const handleDragStart = useCallback(
    (index: number) => {
      if (!enabled) return

      // 延迟启动拖拽，避免误触
      dragTimerRef.current = setTimeout(() => {
        if (!canStartGesture('drag')) {
          return
        }

        startGesture('drag')
        setDragState({
          isDragging: true,
          dragIndex: index,
          hoverIndex: null,
        })

        // 触觉反馈
        triggerHaptic('medium')
      }, delay)
    },
    [enabled, delay, triggerHaptic, startGesture, canStartGesture]
  )

  /**
   * 取消拖拽启动
   */
  const cancelDragStart = useCallback(() => {
    if (dragTimerRef.current) {
      clearTimeout(dragTimerRef.current)
    }
  }, [])

  /**
   * 拖拽经过
   */
  const handleDragOver = useCallback(
    (index: number) => {
      if (!dragState.isDragging || dragState.dragIndex === null) return

      if (index !== dragState.hoverIndex) {
        setDragState((prev) => ({
          ...prev,
          hoverIndex: index,
        }))

        // 轻微震动反馈
        triggerHaptic('light')
      }
    },
    [dragState.isDragging, dragState.dragIndex, dragState.hoverIndex, triggerHaptic]
  )

  /**
   * 结束拖拽
   */
  const handleDragEnd = useCallback(() => {
    cancelDragStart()

    if (!dragState.isDragging || dragState.dragIndex === null) {
      endGesture('drag')
      return
    }

    const { dragIndex, hoverIndex } = dragState

    // 如果有目标位置且不是原位置，执行重排序
    if (hoverIndex !== null && hoverIndex !== dragIndex) {
      const newItems = [...items]
      const [draggedItem] = newItems.splice(dragIndex, 1)
      newItems.splice(hoverIndex, 0, draggedItem)

      onReorder(newItems)

      // 成功反馈
      triggerHaptic('success')
    }

    setDragState({
      isDragging: false,
      dragIndex: null,
      hoverIndex: null,
    })

    endGesture('drag')
  }, [
    dragState,
    items,
    onReorder,
    triggerHaptic,
    cancelDragStart,
    endGesture,
  ])

  /**
   * 获取拖拽项的样式
   */
  const getDragItemStyle = useCallback(
    (index: number) => {
      if (!dragState.isDragging) return {}

      if (index === dragState.dragIndex) {
        return {
          opacity: 0.5,
          transform: 'scale(1.05)',
        }
      }

      return {}
    },
    [dragState.isDragging, dragState.dragIndex]
  )

  /**
   * 是否显示插入指示器
   */
  const showInsertIndicator = useCallback(
    (index: number) => {
      return dragState.isDragging && dragState.hoverIndex === index
    },
    [dragState.isDragging, dragState.hoverIndex]
  )

  return {
    isDragging: dragState.isDragging,
    dragIndex: dragState.dragIndex,
    hoverIndex: dragState.hoverIndex,
    handleDragStart,
    handleDragOver,
    handleDragEnd,
    cancelDragStart,
    getDragItemStyle,
    showInsertIndicator,
  }
}
